<template>
  <div class="player-wrapper" v-show="playlist.length > 0">
    <!-- 全屏播放器 -->
    <transition
      name="normal"
      @enter="enter"
      @after-enter="afterEnter"
      @leave="leave"
      @after-leave="afterLeave"
      >
      <div class="normal-player" ref="normalPlayer" v-show="fullScreen">
        <div class="player-content">
          <div class="top">
            <h1 class="title">{{currentSong.name}}</h1>
            <div class="singer">{{currentSong.artist}}</div>
            <i
              class="icon-back back-btn"
              @click="handleNormalPlayerClose"
              ></i>
          </div>
          <div class="center">
            <swiper :options="swiperOption" ref="mySwiper">
              <!-- slides -->
              <swiper-slide>
                <div class="cd-wrapper">
                  <div class="cd" ref="cd">
                    <img :src="currentSong.albumpic" :class="cdClass" />
                  </div>
                  <p class="lyric" v-if="lyricList[curLyricIndex]">
                    {{lyricList[curLyricIndex].lineLyric}}
                  </p>
                  <p class="lyric" v-else>正在加载歌词...</p>
                </div>
              </swiper-slide>
              <swiper-slide>
                <scroll
                  class="scroll-wrapper"
                  :data="lyricList"
                  ref="lyricScroll"
                  >
                  <ul class="lyric-list">
                    <li v-for="(lyric, index) in lyricList" :key="index">
                      <p
                        :class="{'active': curLyricIndex === index}"
                        ref="lyricLine"
                        >
                        {{lyric.lineLyric}}
                      </p>
                    </li>
                  </ul>
                </scroll>
              </swiper-slide>
              <!-- Optional controls -->
              <div class="swiper-pagination"  slot="pagination"></div>
            </swiper>
          </div>
          <div class="bottom">
            <div class="progress-wrap">
              <span class="start-time">{{format(currentTime)}}</span>
              <div class="progress">
                <progress-bar
                  :percent="percent"
                  @percentChange="handlePercentChange"
                  ></progress-bar>
              </div>
              <span class="end-time">{{format(currentSong.duration)}}</span>
            </div>
            <audio
              :src="songUrl"
              ref="audio"
              @timeupdate="updateTime"
              @ended="end"
              @canplay="ready"
              ></audio>
            <div class="btn-group">
              <i :class="iconMode" @click="handleModeChange"></i>
              <i class="icon-prev" @click="handlePrev"></i>
              <i
                class="play"
                :class="playBtnClass"
                @click="handlePlayBtn"></i>
              <i class="icon-next" @click="handleNext"></i>
              <!-- 收藏按钮 -->
              <i
                :class="getFavoriteIcon(currentSong)"
                @click="toggleFavorite(currentSong)"
                ></i>
            </div>
          </div>
        </div>
        <div class="bg-image">
          <img
            :src="currentSong.albumpic" />
        </div>
      </div>
    </transition>
    <!-- 迷你播放器 -->
    <transition name="mini">
      <div
        class="mini-player"
        v-show="!fullScreen"
        @click="handleMiniPlayerClose"
        >
        <div class="cd" :class="cdClass" ref="miniCd">
          <img :src="currentSong.albumpic" />
        </div>
        <div class="desc">
          <p class="title">{{currentSong.name}}</p>
          <p class="singer">{{currentSong.artist}}</p>
        </div>
        <div class="btn-group">
          <!-- 播放按钮 -->
          <progress-circle :radius="28" :percent="percent">
            <i
              class="play"
              :class="playMiniBtnClass"
              @click.stop="handlePlayBtn"
              ></i>
          </progress-circle>
          <!-- 播放歌曲列表 -->
          <i
            class="icon-playlist playlist"
            @click.stop="showPlaylist"
            ></i>
        </div>
      </div>
    </transition>
    <!-- 歌曲列表 -->
    <playlist ref="playlist"></playlist>
  </div>
</template>

<script>
import { mapGetters, mapMutations, mapActions } from 'vuex'
import animations from 'create-keyframe-animation'
import { prefixStyle } from 'common/js/dom'
import { getSongUrl, getSongLyric } from 'api'
import { playMode } from 'common/js/config'
import { playerMixin } from 'common/js/mixin'
import ProgressBar from 'base/progress/progress'
import ProgressCircle from 'base/progress-circle/progress-circle'
import Scroll from 'base/scroll/scroll'
import Playlist from 'components/playlist/playlist'

const transform = prefixStyle('transform')

export default {
  name: 'player',
  mixins: [playerMixin],
  components: {
    ProgressBar,
    ProgressCircle,
    Scroll,
    Playlist
  },
  data () {
    return {
      songUrl: '',
      currentTime: 0,
      lyricList: [],
      curLyricIndex: -1,
      swiperOption: {
        pagination: '.swiper-pagination',
        virtualTranslate: true, // 取消 Swiper 自带的位移
        longSwipesRatio: 0.3, // 触发 swiper 所需要的最小拖动距离比例
        shortSwipes: false // 快速短距离的拖动不触发 Swiper
      }
    }
  },
  mounted () {
    this.touch = {}

    this.swiper.on('touchStart', (swiper, e) => {
      this.touch.startY = e.touches[0].pageY
    })

    this.swiper.on('touchMove', (swiper, e) => {
      let diff = swiper.touches.diff // 获取 X 轴滑动距离

      // X 轴滑动距离绝对值
      let deltaX = Math.abs(diff)

      // Y 轴滑动距离绝对值
      const deltaY = Math.abs(e.touches[0].pageY - this.touch.startY)

      // 如果 Y 轴滑动距离大于 X 轴滑动距离，则说明是纵向滚动(歌词)
      if (deltaY > deltaX) {
        return
      }

      // 当前 slide 距离左侧的距离
      // swiper.activeIndex 获取的是当前显示的 slide 对应下标
      const left = swiper.activeIndex === 0 ? 0 : -swiper.width

      // 计算位移距离
      const offsetWidth = Math.min(0, Math.max(-swiper.width, left + diff))

      // 实现位移
      const lyricSlide = swiper.slides[1] // 获取第二个 slide 元素(歌词)
      lyricSlide.style.transform = `translate3d(${offsetWidth}px, 0, 0)`
      swiper.slides[0].style.opacity = 1 - Math.abs(offsetWidth / swiper.width)
    })

    this.swiper.on('touchEnd', (swiper, e) => {
      let offsetWidth
      let opacity

      let diff = swiper.touches.diff // 获取滑动距离

      let deltaX = Math.abs(diff / swiper.width) // 滑动距离与 slide 宽度的比例

      const lyricSlide = swiper.slides[1] // 获取第二个 slide 元素(歌词)

      if (swiper.activeIndex === 0) {
        // activeIndex 为 0 时，即当前显示的 slide 为 CD 区域
        if (diff < 0 && deltaX >= 0.3) {
          // 向左滑(diff < 0)并且滑动比例大于等于 0.3 时
          offsetWidth = -swiper.width
          opacity = 0
          swiper.activeIndex = 1 // 设置当前 slide 的 index 为 1 (歌词)
        } else {
          offsetWidth = 0
          opacity = 1
        }
      } else {
        // activeIndex 为 1 时，即当前显示的 slide 为歌词区域
        if (diff > 0 && deltaX >= 0.3) {
          // 向右滑(diff > 0)并且滑动比例大于等于 0.3 时
          offsetWidth = 0
          opacity = 1
          swiper.activeIndex = 0 // 设置当前 slide 的 index 为 0 (CD)
        } else {
          offsetWidth = -swiper.width
          opacity = 0
        }
      }

      lyricSlide.style.transform = `translate3d(${offsetWidth}px, 0, 0)`
      swiper.slides[0].style.opacity = opacity
    })
  },
  computed: {
    playBtnClass () {
      return this.playing ? 'icon-pause' : 'icon-play'
    },
    playMiniBtnClass () {
      return this.playing ? 'icon-pause-mini' : 'icon-play-mini'
    },
    cdClass () {
      return this.playing ? 'cd-play' : 'cd-pause'
    },
    percent () {
      return this.currentTime / this.currentSong.duration
    },
    swiper () {
      return this.$refs.mySwiper.swiper
    },
    ...mapGetters([
      'fullScreen',
      'playing',
      'currentIndex'
    ])
  },
  methods: {
    handleNormalPlayerClose () {
      this.setFullScreen(false)
    },
    handleMiniPlayerClose () {
      this.setFullScreen(true)
    },
    enter (el, done) {
      // 获取 x 轴距离、y 轴距离、缩放比例
      const { x, y, scale } = this._getPosAndScale()

      let animation = {
        // 动画开始的瞬间，将大 CD 移动并缩小到左下角
        0: {
          transform: `translate3d(${-x}px, ${y}px, 0) scale(${scale})`
        },
        // 动画执行中，让大 CD 回到原来位置并且恢复到原来的 1.1 倍大小
        60: {
          transform: `translate3d(0, 0, 0) scale(1.1)`
        },
        // 动画完，让大 CD 回到原来位置并且恢复原来大小
        100: {
          transform: `translate3d(0, 0, 0) scale(1)`
        }
      }

      // 使用 create-keyframe-animation 插件创建 CSS3 帧动画
      animations.registerAnimation({
        name: 'move',
        animation,
        // optional presets for when actually running the animation
        presets: {
          duration: 400, // 持续时间
          easing: 'linear' // 缓动函数
        }
      })

      // 使用 create-keyframe-animation 插件执行 CSS3 帧动画
      // 第三个参数接收回调函数，我们调用了 done
      animations.runAnimation(this.$refs.cd, 'move', done)
    },
    afterEnter (el) {
      // 使用 create-keyframe-animation 插件移除 CSS3 帧动画
      animations.unregisterAnimation('move')

      // 清空基础播放器 CD 的 animation 属性值
      this.$refs.cd.style.animation = ''
    },
    leave (el, done) {
      // 获取 x 轴距离、y 轴距离、缩放比例
      const { x, y, scale } = this._getPosAndScale()

      this.$refs.cd.style.transition = 'all .3s'

      this.$refs.cd.style[transform] = `translate3d(${-x}px, ${y}px, 0) scale(${scale})`

      this.$refs.cd.addEventListener('transitionend', done)
    },
    afterLeave (el) {
      this.$refs.cd.style.transition = ''
      this.$refs.cd.style[transform] = ''
    },
    handlePlayBtn () {
      this.setPlayingState(!this.playing)
    },
    handlePrev () {
      let index = this.currentIndex - 1
      if (index < 0) {
        index = this.playlist.length - 1
      }

      this.setCurrentIndex(index)
      this.$refs.audio.currentTime = 0

      if (!this.playing) {
        this.handlePlayBtn()
      }
    },
    handleNext () {
      let index = this.currentIndex + 1
      if (index === this.playlist.length) {
        index = 0
      }

      this.setCurrentIndex(index)
      this.$refs.audio.currentTime = 0

      if (!this.playing) {
        this.handlePlayBtn()
      }
    },
    updateTime (e) {
      // e.target 就是 audio 标签，自带 currentTime 属性(当前播放时间)
      // currentTime 是一个可读写属性，即可以获取也可以设置
      this.currentTime = e.target.currentTime
      // console.log(this.currentTime)
    },
    format (interval) {
      // 对 interval 向下取整，inerval | 0 相当于 Math.floor(interval)
      interval = interval | 0

      // 除以 60 并且向下取整
      const minutes = interval / 60 | 0

      // 模 60
      const seconds = this._pad(interval % 60)

      return `${minutes}:${seconds}`
    },
    handlePercentChange (newPercent) {
      this.$refs.audio.currentTime = this.currentSong.duration * newPercent

      if (!this.playing) {
        this.handlePlayBtn()
      }
    },
    end () {
      if (this.mode === playMode.loop) {
        // 当前播放模式为 loop(循环)，则调用 loop 方法循环播放
        this.loop()
      } else {
        // 否则，不为 loop，则切换到下一首
        this.handleNext()
      }
    },
    loop () {
      this.$refs.audio.currentTime = 0
      this.$refs.audio.play()
    },
    scroll () {
      if (this.curLyricIndex > 5) {
        let lineEl = this.$refs.lyricLine[this.curLyricIndex - 5]
        this.$refs.lyricScroll.scrollToEl(lineEl, 1000)
      } else {
        this.$refs.lyricScroll.scrollTo(0, 0, 1000)
      }
    },
    showPlaylist () {
      this.$refs.playlist.show()
    },
    ready () {
      this.savePlayHistory(this.currentSong)
    },
    _getPosAndScale () {
      const miniCdWidth = 42 // 迷你播放器中小圆宽度
      const miniCdLeft = 41 // 迷你播放器中小圆中心点到左边的距离
      const miniCdBottom = 30 // 迷你播放器中小圆中心点到底边的距离

      const cdWidth = 280 // 播放器中 CD 宽度
      const cdPosition = this.$refs.cd.getBoundingClientRect()
      const cdLeft = cdPosition.left + 140 // 播放器 CD 中心点到左边的距离
      const cdBottom = cdPosition.top + 140 // 播放器 CD 中心点到底边的距离

      const scale = miniCdWidth / cdWidth // 初始缩放比例
      const x = cdLeft - miniCdLeft // x 轴偏移距离
      const y = cdBottom - miniCdBottom // y 轴偏移距离

      return {
        x,
        y,
        scale
      }
    },
    _getSongUrl () {
      getSongUrl({
        rid: this.currentSong.rid
      }).then((song) => {
        // console.log('This song is:', song)
        this.songUrl = song.url

        this.$nextTick(() => {
          if (!this.playing) {
            return
          }
          this.$refs.audio.play()
        })
      })
    },
    _getSongLyric () {
      getSongLyric({
        rid: this.currentSong.rid
      }).then((data) => {
        this.lyricList = [...data.lyricList,
          {
            lineLyric: '',
            time: '1000'
          }
        ]
        // console.log('lyric is:', data.lyricList)
      })
    },
    _pad (num, n = 2) {
      // num 是要补 0 的数字
      // n 的作用是可以控制补几个 0
      let len = num.toString().length
      while (len < n) {
        num = '0' + num
        len++
      }
      return num
    },
    ...mapMutations({
      setFullScreen: 'SET_FULL_SCREEN'
    }),
    ...mapActions([
      'savePlayHistory'
    ])
  },
  watch: {
    currentSong (newSong, oldSong) {
      if (!newSong.rid) {
        return
      }
      // 如果新旧歌曲的 rid 是一样的，说明是同一首歌，什么都不做
      if (newSong.rid === oldSong.rid) {
        return
      }
      this.$refs.audio.currentTime = 0
      this._getSongUrl()
      this._getSongLyric()
    },
    playing (newVal) {
      const audio = this.$refs.audio // 将 audio 缓存

      if (this.songUrl) {
        // 当 songUrl 不为空时，
        // newVal 为 true，则播放，为 false，则暂停
        newVal ? audio.play() : audio.pause()
      }
    },
    currentTime (newVal) {
      let index = this.lyricList.findIndex((item) => {
        return newVal < item.time
      })
      // console.log(newVal)

      this.curLyricIndex = index - 1
      // console.log(index)
      this.scroll()
    }
  }
}
</script>

<style lang="stylus" scoped>
  @import '~common/stylus/variable.styl'
  .player-wrapper {
    .normal-player {
      position: fixed
      top: 0
      right: 0
      left: 0
      bottom: 0
      z-index: 101
      background: $color-background
      .bg-image {
        position: absolute
        top: 0
        right: 0
        bottom: 0
        left: 0
        img {
          height: 100%
          filter: blur(10px) // 高斯模糊
        }
      }
      .player-content {
        position: absolute
        top: 0
        right: 0
        bottom: 0
        left: 0
        z-index: 100
        background: $color-background-d
        display: flex
        flex-direction: column
        .top {
          text-align: center
          .title {
            height: 44px
            line-height: 44px
            font-size: $font-size-medium-x
          }
          .singer {
            font-size: $font-size-small
          }
          .back-btn {
            position: absolute
            left: 0
            top: 0
            font-size: 20px
            padding: 10px
            color: $color-theme
          }
        }
        .center {
          flex: 1
          >>> .swiper-container {
            height: 100%
          }
          >>> .swiper-pagination-bullets {
            bottom: 30px
          }
          >>> .swiper-pagination-bullet {
            background: $color-text
            opacity: 0.6
          }
          >>> .swiper-pagination-bullet-active {
            width: 20px
            border-radius: 10px
            opacity: 1
          }
          .cd-wrapper {
            height: 100%
            display: flex
            flex-direction: column
            justify-content: center
            .cd {
              position relative
              width: 280px
              height: 280px
              background: $color-background-d
              border-radius: 50%
              margin: 0 auto
              box-shadow: 0 0 4px 8px $color-background-d
              overflow: hidden
              img {
                width: 100%
              }
            }
            .lyric {
              margin-top: 28px
              text-align: center
              font-size: $font-size-small
              color: $color-text-l
            }
          }
          .scroll-wrapper {
            overflow: hidden
            position: absolute
            top: 20px
            right: 0
            bottom: 68px
            left: 0
            .lyric-list {
              text-align: center
              font-size: $font-size-small
              p {
                line-height: 30px
                color: $color-text-l
                &.active {
                  color: $color-text
                }
              }
            }
          }
        }
        .bottom {
          height: 120px
          padding: 0 28px
          .btn-group {
            display: flex
            i {
              flex: 1
              text-align: center
              font-size: 28px
              align-self: center
              color: $color-theme
              &.play {
                font-size: 36px
              }
              &.icon-favorite {
                color: $color-sub-theme
              }
            }
          }
          .progress-wrap {
            display: flex
            // background: blue
            margin-bottom: 20px
            padding: 0 20px
            font-size: $font-size-small
            .progress {
              flex: 1
              align-self: center
              padding: 0 10px
            }
          }
        }
      }
    }
    .mini-player {
      position: absolute
      bottom: 0
      left: 0
      right: 0
      z-index: 999
      height: 60px
      background: $color-highlight-background
      display: flex
      padding: 0 20px
      .cd {
        width: 42px
        height: 42px
        border-radius: 50%
        background: #eee
        margin-top: 9px
        overflow: hidden
        img {
          width: 100%
          height: 100%
        }
      }
      .desc {
        flex: 1
        margin-left: 10px
        .title {
          margin-top: 14px
          font-size: $font-size-medium
        }
        .singer {
          margin-top: 8px
          font-size: $font-size-small
          color: $color-text-d
        }
      }
      .btn-group {
        display: flex
        font-size: 24px
        color: $color-theme-d
        margin-top: 18px
        .play {
          font-size: 28px
          position: absolute
          top: 0
          left: 0
        }
        .playlist {
          // align-self: center
        }
      }
    }
  }

  .normal-enter, .normal-leave-to {
    opacity: 0
    .top {
      opacity: 0
      transform: translate3d(0, -200px, 0)
    }
    .bottom {
      opacity: 0
      transform: translate3d(0, 200px, 0)
    }
  }
  .normal-enter-active, .normal-leave-active {
    transition: all .3s
    .top {
      transition: all .3s
    }
    .bottom {
      transition: all .3s
    }
  }

  .mini-enter, .mini-leave-to {
    opacity: 0
  }
  .mini-enter-active, .mini-leave-active {
    transition: all .3s
  }

  @keyframes rotate {
    0% {
      transform: rotate(0)
    }
    100% {
      transform: rotate(360deg)
    }
  }

  .cd-play {
    animation: rotate 10s linear infinite
  }

  .cd-pause {
    animation: rotate 10s linear infinite paused
  }

</style>
